package com.sunchp.nio.sample.reactor;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;

public class ThreadPoolHandler implements Handler {
    private ExecutorService executorService;

    public ThreadPoolHandler(ExecutorService executorService) {
        this.executorService = executorService;
    }

    @Override
    public void handle(SelectionKey key) {
        this.executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    SocketChannel socketChannel = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    buffer.clear();
                    int byteRead = socketChannel.read(buffer);

                    while (byteRead > 0) {
                        System.out.println(byteRead);
                        buffer.flip();
                        while (buffer.hasRemaining()) {
                            socketChannel.write(buffer);
                        }

                        byteRead = socketChannel.read(buffer);
                    }

                    if (byteRead < 0) {
                        System.out.println("client close connect");
                        socketChannel.close();
                        key.cancel();
                        return;
                    }

                    System.out.println(byteRead);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
